#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__

#include <iostream>
#include <functional>
#include "Comm.hpp"
#include "InetAddr.hpp"
#include "User.hpp"
#include "ThreadPool.hpp"

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1";
const static uint16_t gdefaultport = 8080;

using adduser_t = std::function<void(InetAddr &id)>;
using route_t = std::function<void(int sockfd, const std::string &message)>;
using task_t = std::function<void()>;
using remove_t = std::function<void(InetAddr& id)>;

using namespace LogModule;
using namespace ThreadPoolModule;

class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port), _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1.创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket:" << strerror(errno);
            DIE(SOCKET_ERR);
        }
        // 成功
        LOG(LogLevel::INFO) << "socket succeed, sockfd :" << _sockfd;

        // //注入网络信息
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // local.sin_port = htons(_port);  //要被发到网络中
        // //local.sin_addr.s_addr = ::inet_addr(_ip.c_str()); //string ip->4bytes
        // //in_addr是一个结构体,里面唯一的成员是类型为in_addr_t的变量
        // local.sin_addr.s_addr = INADDR_ANY;

        // 绑定:设置进内核里
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind:" << strerror(errno);
            DIE(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind succeed";
    }
    void RegisterService(adduser_t adduser, route_t route, remove_t removeuser)
    {
        _adduser = adduser;
        _route = route;
        _remove = removeuser;
    }
    void Start()
    {
        _isrunning = true;
        while (1)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (sockaddr *)(&peer), &len);
            if (n > 0)
            {
                // 1.消息内容
                // 2.谁发的
                //  uint16_t clientport = ::ntohs(peer.sin_port);
                //  std::string clientip = ::inet_ntoa(peer.sin_addr);

                InetAddr cli(peer);
                inbuffer[n] = 0;
                std::string message;

                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    // 移除逻辑
                    _remove(cli);
                    message = cli.Addr()+"# bye";
                }
                else
                { 
                    message = cli.Addr() + "# " + inbuffer;
                    // 新增用户
                    _adduser(cli);
                }

                // 构建转发任务，推给线程池，让线程池转发
                task_t task = std::bind(UdpServer::_route, _sockfd, message);
                ThreadPool<task_t>::GetInstance()->Equeue(task);

                // std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port())+"#"
                //     +inbuffer;
                // LOG(LogLevel::DEBUG)<<clientinfo;

                // std::string echo_str = "echo#";
                // echo_str += inbuffer;
                // ::sendto(_sockfd, echo_str.c_str(), echo_str.size(), 0, (sockaddr*)(&peer), sizeof(peer));
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;
    // uint16_t _port; //服务器的端口号
    // std::string _ip;  正常不需要ip地址
    InetAddr _addr;
    bool _isrunning;

    adduser_t _adduser;
    route_t _route;
    remove_t _remove;
};

#endif